package com.bailiny.basicUtils;

import com.google.common.base.Objects;
import com.google.common.collect.ComparisonChain;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 常见Object方法
 */
public class ObjectDemo {

    @Test
    public void equalsDemo() {
        Objects.equal("a", "a"); // returns true
        Objects.equal("a", null);
        Objects.equal(null, "a"); // returns false
        Objects.equal(null, null); // returns true
    }

    /**
     * 用对象的所有字段作散列[hash]运算应当更简单。Guava的Objects.hashCode(Object...)会对传入的字段序列计算出合理的、
     * 顺序敏感的散列值。你可以使用Objects.hashCode(field1, field2, …, fieldn)来代替手动计算散列值。
     */
    @Test
    public void hashCodeDemo() {
        String s = "fdsg";
        int i = Objects.hashCode(s);
    }

    @Test
    public void compareToDemo() {
        List<Person> list = new ArrayList<>();
        list.add(new Person("a", "zhang", 67));
        list.add(new Person("b", "zhang", 66));
        list.add(new Person("b", "yang", 77));
        Collections.sort(list);
        list.forEach(p -> {
            System.out.println(p.getFirstName() + "," + p.getLastName() + ", " + p.getZipCode());
        });
    }

    class Person implements Comparable<Person> {
        private String firstName;
        private String lastName;
        private int zipCode;

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public int getZipCode() {
            return zipCode;
        }

        public void setZipCode(int zipCode) {
            this.zipCode = zipCode;
        }

        public Person() {
        }

        Person(String firstName, String lastName, int zipCode) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.zipCode = zipCode;
        }

        /*public int compareTo(Person other) {
            int cmp = lastName.compareTo(other.lastName);
            if (cmp != 0) {
                return cmp;
            }
            cmp = firstName.compareTo(other.firstName);
            if (cmp != 0) {
                return cmp;
            }
            return Integer.compare(zipCode, other.zipCode);
        }*/

        public int compareTo(Person other) {
            return ComparisonChain.start()
                    .compare(this.lastName, other.lastName)
                    .compare(this.firstName, other.firstName)
                    .compare(this.zipCode, other.zipCode)
                    .result();
        }
    }
}
